package com.luxsoft.siipap.em.replica.ui.tasks;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.List;

import javax.swing.SwingWorker;

import org.apache.log4j.Appender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import com.luxsoft.siipap.em.replica.importadores.ImportacionCanceledException;
import com.luxsoft.siipap.em.replica.importadores.cxc.ImportadorDeClientes;
import com.luxsoft.siipap.model.Periodo;
import com.luxsoft.siipap.model.core.Cliente;
import com.luxsoft.siipap.service.ServiceLocator2;
import com.luxsoft.siipap.util.DBUtils;

/**
 * Componente grafico para la importacion de clientes
 * 
 * @author Ruben Cancino
 *
 */
public class ImportadorDeClientesTask {

	public ImportadorDeClientesTask() {
		
	}
	
	public void execute(){
		Logger logger=Logger.getLogger(ImportadorDeClientes.class);
		logger.setLevel(Level.INFO);
		TaskDialog dialog=new TaskDialog("Importar clientes");
		final SwingWorker worker=new Importador(dialog);
		dialog.registerWorker(worker);		
		Appender appender=dialog.registerDetailLogHandler(logger);
		dialog.open();
		logger.removeAppender(appender);
		
	}
	
	
	
	private class Importador extends SwingWorker<String,String>{
		
		private final TaskDialog dialog;
		
		public Importador(final TaskDialog dialog){
			this.dialog=dialog;
		}

		@Override
		protected String doInBackground() throws Exception {
			
			final int total=ServiceLocator2.getAnalisisJdbcTemplate()
				.queryForInt("SELECT count(*) FROM CLIENTES_TO_MYSQL2 WHERE FRECUENTE=1 order by CLAVE desc");
			
			ImportadorDeClientes importer=new ImportadorDeClientes(){

				protected Cliente procesar(final ResultSet rs)throws SQLException{
					int i=rs.getRow()+1;
					setProgress(i*100/total);
					
					if(isCancelled())
						throw new ImportacionCanceledException("Imporacion de clientes cancelada");
					Cliente res=super.procesar(rs);
					
					
					String pattern="Importando/Actualizando:  {0} de: {1}";
					publish(MessageFormat.format(pattern, i,total));
					return res;
				}
				
			};
			importer.importar(Periodo.hoy());
			return "OK";
		}

		@Override
		protected void process(List<String> chunks) {
			for(String s:chunks){
				dialog.getHeader().setDescription(s);
			}
		}
		
		
	}
	
	public static void main(String[] args) {
		DBUtils.whereWeAre();
		new ImportadorDeClientesTask().execute();
	}

}
